package edu.uclm.esi.tysw.tusEntradas.acciones;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import edu.uclm.esi.tysw.tusEntradas.domain.Butaca;
import edu.uclm.esi.tysw.tusEntradas.domain.Recintos;

public class AltaRecinto extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Exception exception;
	
	@Override
	public String execute() {
		try {
			Recintos nuevo = (Recintos) ActionContext.getContext().getSession().get("nuevoRecinto");
			nuevo.insert();
			ActionContext.getContext().getSession().remove("nuevoRecinto");
			
			@SuppressWarnings("unchecked")
			ArrayList<Butaca> listaButacas = (ArrayList<Butaca>) ActionContext.getContext().getSession().get("listaButacas");
			String numerosCreados = ",";
	   		if (listaButacas != null) {
		   		for (int i=0; i < listaButacas.size();i++) {
		   			numerosCreados = numerosCreados + listaButacas.get(i).getNumero() + ",";
		   		}
		   		for (int j=1; j <= nuevo.getFilas() * nuevo.getColumnas(); j++) {
		   			if (!numerosCreados.contains("," + Integer.toString(j) + ",")) {
		   				double pvp = 0;
		   				listaButacas.add(new Butaca (j, pvp, "Hueco", nuevo.getNombre()));
		   			}
		   		}
	   		}
			ActionContext.getContext().getSession().remove("listaButacas");
			Iterator<Butaca> itButaca = listaButacas.iterator();
			while (itButaca.hasNext()){
				itButaca.next().insert();
			}
			return SUCCESS;
		} catch (SQLException e) {
			this.exception=e;
			return ERROR;
		} 
	}

	public void setException(Exception exception) {
		this.exception = exception;
	}

	public Exception getException() {
		return exception;
	}
}
